package me.leiusual.sharing.ui.cart.adapter

import android.view.View
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.extensions.LayoutContainer
import kotlinx.android.synthetic.main.layout_amount.view.*
import kotlinx.android.synthetic.main.view_holder_cart_home_child.*
import me.leiusual.sharing.R
import me.leiusual.sharing.api.model.cartdetail.CartX
import me.leiusual.sharing.util.extension.setImageUrl
import me.leiusual.sharing.util.extension.spToPx
import me.leiusual.sharing.util.extension.toSpanned
import me.leiusual.sharing.widget.AmountView
import timber.log.Timber

/**
 * author: leiusual
 * create on: 2019-07-27
 * description:
 */
class CartHomeChildViewHolder(
    override val containerView: View,
    private val changeListener: () -> Unit,
    private val amountListener: (CartX) -> Unit
) : RecyclerView.ViewHolder(containerView), LayoutContainer, View.OnClickListener, AmountView.Listener {

  lateinit var cartX: CartX

  init {
    check_box.setOnClickListener(this)
    amount_view.listener = this
  }

  fun bind(cartX: CartX) {
    this.cartX = cartX

    // 选中状态
    check_box.isChecked = cartX.checked!!

    // 图片
    image_view.setImageUrl(cartX.productImage)

    // 商品名称
    text_view_product_name.text = cartX.modelName

    // 商区
    if (cartX.referStoreName != null) {
      text_view_area.text = cartX.referStoreName + """   """ + cartX.storeAreaName
    } else {
      text_view_area.text = cartX.storeAreaName
    }

    // 价格
    val size = 10f.spToPx(containerView.context)
    val builder = StringBuilder()
    val modelDesc = cartX.modelDesc
    if (!modelDesc.isNullOrBlank()) {
      builder.append("$modelDesc<br/>")
    }

    builder.append("""<font color="red">""")
    cartX.priceVos.forEach {
      when (it.coinType) {
        "RMB" -> builder.append("""<size_$size>￥</size_$size>""")
        else -> builder.append("""<size_$size>分</size_$size>""")
      }
      builder.append("""${it.pointCoinString}  """)
    }
    builder.append("""</font>""")
    text_view_price.text = builder.toString().toSpanned()

    // 数量、库存
    amount_view.etAmount.setText(cartX.amount.toString())
    amount_view.maxAmount = cartX.inventory
  }

  override fun onClick(v: View?) {
    when (v?.id) {
      R.id.check_box -> {
        cartX.checked = check_box.isChecked
        changeListener()
      }
    }
  }

  override fun onAmountClicked(amount: Int) {
    Timber.v("amount = %s", amount)
    cartX.amount = amount
    changeListener()
    amountListener(cartX)
  }
}